package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.ParameterException;
import com.demo.dao.TeamDao;
import com.demo.dao.TeamProfileDao;
import com.demo.domain.TeamComposition;
import com.demo.domain.TeamProfile;
import com.demo.service.TeamCompositionService;
import com.demo.service.TeamProfileService;
import com.demo.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

@Service
public class TeamServiceImpl extends ServiceImpl<TeamDao, TeamProfile> implements TeamService {

    @Autowired
    TeamDao teamDao;

    @Autowired
    private TeamProfileDao teamProfileDao;

    @Autowired
    private TeamProfileService teamProfileService;

    @Autowired
    private TeamCompositionService teamCompositionService;


    //通过队伍id显示队伍详情
    @Override
    public TeamProfile getTeamProfileById(Long tpId) throws ParameterException {
        if (tpId <= 0l) {
            throw new ParameterException("tpId数值非法");
        }
        LambdaQueryWrapper<TeamProfile> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(TeamProfile::getTpId,tpId);
        return teamDao.selectOne(wrapper);
    }

    @Override
    @Transactional
    public String organizeTeamInfoAndMember(TeamProfile teamProfile, List<TeamComposition> compositionList, Long uid) throws Exception {
        if (teamProfile == null ) {
            throw new ParameterException("teamProfile为null");
        }
        if (uid==null||uid<0l){
            throw new ParameterException("uid为null或值非法");
        }
        if (compositionList==null||compositionList.size()<0){
            throw new ParameterException("compositionList为空");
        }
        boolean quantify=true;
        try {
            List<TeamComposition> noLeaderList=new ArrayList<>();//去除当前用户的列表
            //对成员列表进行检查
            for (TeamComposition composition:compositionList){
                //检查是否每一个元素的所有必要信息都进行填写
                if (composition.getMemberType()>2||composition.getMemberType()<0
                ||composition.getUid()==null||composition.getUid()<0l
                ||composition.getUrealname()==null||composition.getUrealname().equals("")){
                    quantify=false;
                    throw new Exception("成员列表中有信息未填写完全");
                }
                //检查当前用户的身份是否为队长（必须为队长）
                if (composition.getUid().equals(uid)&&composition.getMemberType()!=1){
                    quantify=false;
                    throw new Exception("当前用户必须为队长");
                }
                //检查除了当前用户的其他成员是否为非队长
                if ((!composition.getUid().equals(uid))&&composition.getMemberType()==1){
                    quantify=false;
                    throw new Exception("其他成员身份必须为非队长");
                }
                if (!composition.getUid().equals(uid)){
                    noLeaderList.add(composition);
                }
            }
            if (noLeaderList.size()!=compositionList.size()-1){
                quantify=false;
                throw new Exception("当前成员列表无创建者本人");
            }
            //组队（在TeamProfile表插入新记录且将当前用户添加为队长）
            String msg = teamProfileService.organizeTeam(teamProfile, uid);
            //插入其余成员
            if (msg.equals("队伍组建成功")){
                //找到刚刚插入的新队伍的队伍id
                LambdaQueryWrapper<TeamProfile> newWrapper = new LambdaQueryWrapper<>();
                newWrapper.eq(TeamProfile::getTpTeamName, teamProfile.getTpTeamName());
                TeamProfile newTeam = teamProfileDao.selectOne(newWrapper);
                if (newTeam!=null&&newTeam.getTpId()!=null&&newTeam.getTpId()>0l){
                    //获取新队伍的teamId并为composition设置该id
                    Long teamId=newTeam.getTpId();
                    for (TeamComposition composition:noLeaderList){
                        composition.setTeamId(teamId);
                        boolean flag=teamCompositionService.increTeamMember(composition,uid);
                        //插入失败时，抛错回滚
                        if (!flag){
                            throw new Exception("成员插入失败");
                        }
                    }
                    return "队伍组建成功！";
                }
                return "队伍组建失败";
            }
            return msg;
        }catch (Exception e){
            System.out.println(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
            //若是成员列表不合要求，则返回提示
            if (quantify==false){
                return e.getMessage();
            }
            return "组建队伍失败，请检查是否正确填写信息或联系管理员重新尝试";
        }
    }


}
